import { PluginCreator } from 'postcss';
import config from '../config';

// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Plugin {
  export interface Options { }
}

export const postcssUnit2rpx: PluginCreator<Plugin.Options> = (options = {}) => {
  return {
    postcssPlugin: 'postcss-unit2rpx',
    Root(root, postcss) {
      root.walkRules((rule, index) => {
        root.walkDecls((decl) => {
          decl.value = decl.value.replace(
            /([0-9.]+)(px|rem)/gi,
            (match, size, unit) => {
              if (unit === 'px' && config.style.unit.px2rpx) {
                return `${size}rpx`;
              } else if (unit === 'rem' && config.style.unit.rem2rpx) {
                return `${size * 100}rpx`;
              }
              return match;
            }
          );
        });
      });
    }
  }
}

postcssUnit2rpx.postcss = true